﻿using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class Slot : MonoBehaviour
{
    private  bool isPainted = false;
    public TextMeshPro number;
    /// <summary>
    /// 八边型，五边型,砖石
    /// </summary>
    public GameObject paintEffectPrefab, Pentagonal_type,masonry; // 涂色效果预制体
    /// <summary>
    /// 当前宝石
    /// </summary>
    private GameObject CurrentGems;
    private float effectHeight = 0.5f; // 效果生成高度
    /// <summary>
    /// 当前方块编号
    /// </summary>
    public string id;
    private Renderer _renderer;
    private MaterialPropertyBlock _propBlock;
    /// <summary>
    /// 队列编号
    /// </summary>
    public int QueueId;
    /// <summary>
    /// 粒子效果
    /// </summary>
    private  ParticleSystem explosionEffect, ExplosionNovaWhite;
    /// <summary>
    /// 宝石位置
    /// </summary>
    private Transform gemstonePos;
    /// <summary>
    /// 碰撞组件
    /// </summary>
    private BoxCollider collider;


    /// <summary>
    /// 是否被点亮
    /// </summary>
    /// <returns></returns>
    public bool GetisPainted()
    {
        return isPainted;
    }
    void Awake()
    {
        number = transform.Find("txt").GetComponent<TextMeshPro>();
        //paintEffectPrefab = Resources.Load<GameObject>("gemstonePos/TestGem");
        //Pentagonal_type = Resources.Load<GameObject>("gemstonePos/TestGem 2");
        //masonry = Resources.Load<GameObject>("gemstonePos/TestGem 1");
        _renderer = GetComponent<Renderer>();
        _propBlock = new MaterialPropertyBlock();
        explosionEffect= transform.Find("TinySparkle").GetComponent<ParticleSystem>();
        ExplosionNovaWhite= transform.Find("ExplosionNovaWhite").GetComponent<ParticleSystem>();
        explosionEffect.gameObject.SetActive(false);
        ExplosionNovaWhite.gameObject.SetActive(false);
        gemstonePos = transform.Find("gemstonePos");
        collider = gameObject.GetComponent<BoxCollider>();
    }
    /// <summary>
    /// 初始化
    /// </summary>
   public void Init()
    {
        id = "";
        isPainted = false;
        QueueId = 0;
        explosionEffect.gameObject.SetActive(false);
        ExplosionNovaWhite.gameObject.SetActive(false);
        number.text = "";
        Turn0ffGems();
    }

    /// <summary>
    /// 自己涂色完成效果
    /// </summary>
    public void ColoringEffect()
    {
        if (ExplosionNovaWhite != null)
        {
            ExplosionNovaWhite.gameObject.SetActive(true);
            ExplosionNovaWhite.Play();
            StartCoroutine(DisableAfterPlaying(ExplosionNovaWhite));
        }
    }


    /// <summary>
    /// 全部字母完成播放
    /// </summary>
    public void PlayParticleEffect()
    {
        if (explosionEffect != null)
        {
            explosionEffect.gameObject.SetActive(true);
            explosionEffect.Play();
            StartCoroutine(DisableAfterPlaying(explosionEffect));
        }
    }


    private IEnumerator DisableAfterPlaying(ParticleSystem ps)
    {
        // 等待直到粒子系统完全停止
        while (ps != null && ps.IsAlive(true)) // true表示检查子粒子
        {
            yield return null;
        }

        if (ps != null)
        {
            ps.gameObject.SetActive(false);
            // 如果需要可以清除残留粒子
            ps.Clear();
        }
    }




    /// <summary>
    /// 根据灰度变化
    /// </summary>
    public void Grey_change(float r, float g, float b)
    {
        // 取RGB中的最大值作为灰度（会产生更高对比度）
        float greyValue = Mathf.Max(r, Mathf.Max(g, b));

        // 可选：进一步增加对比度
        greyValue = Mathf.Pow(greyValue, 1.5f);

        greyValue = Mathf.Clamp01(greyValue);

        Color greyColor = new Color(greyValue, greyValue, greyValue);

        _renderer.GetPropertyBlock(_propBlock);
        _propBlock.SetColor("_Color", greyColor);
        _renderer.SetPropertyBlock(_propBlock);
    }


    /// <summary>
    /// 变化颜色
    /// </summary>
    public void Change_color(float num)
    {

        // 验证参数范围 (0-1)
        num = Mathf.Clamp01(num);

        // 使用属性块避免材质实例化
        _renderer.GetPropertyBlock(_propBlock);

        // 兼容不同渲染管线
        string colorProperty = "_Color"; // 默认属性名

        // 自动检测URP/HDRP
        if (IsUsingURPOrHDRP())
        {
            colorProperty = "_BaseColor";
        }

        // 设置灰色值 (RGB相同)
        _propBlock.SetColor(colorProperty, new Color(0.8f-num , 0.8f - num , 0.8f - num));
        _renderer.SetPropertyBlock(_propBlock);
    }
    private bool IsUsingURPOrHDRP()
    {
        // 检测当前渲染管线
#if UNITY_2019_1_OR_NEWER
        return UnityEngine.Rendering.GraphicsSettings.renderPipelineAsset != null;
#else
        return false;
#endif
    }

    // 检查当前格子是否可以涂色
    public bool CanPaint(string currentTargetNumber)
    {
        if (isPainted || number == null) return false;
   
        return number.text == currentTargetNumber;
    }

    public void SetNumber(string s,int num)
    {
        //Debug.Log(s);
        id = s;
        QueueId = num;
        //number.text = id;
    }
    /// <summary>
    /// 显示文本
    /// </summary>
    public void AddText()
    {
        number.enabled = true;
        number.text = id;
    }
    /// <summary>
    /// 关闭性能消耗
    /// </summary>
    public void TurnOffConsumption()
    {
        collider.enabled = false;
        number.gameObject.SetActive(false);
    }

    /// <summary>
    /// 打开有消耗的功能
    /// </summary>
    public void OpenConsumption()
    {
        if(isPainted)
        {
            return;
        }
        collider.enabled = true;
        number.gameObject.SetActive(true);
        number.text = id;
    }

    /// <summary>
    /// 涂色
    /// </summary>
    /// <param name="iswrite">是否需要写入数据</param>
    public void Paint(bool iswrite)
    {
        if(!transform.gameObject.activeInHierarchy)
        {
            return;
        }
        if (!GameInit.instance.MapData.map_color.ContainsKey(id))
        {
            Debug.Log("找不到对应形状");
            return;
        }
        if (isPainted) return;
        isPainted = true;
        // 可以在这里添加涂色效果，如改变颜色
        //number.color = Color.red;
        Vector3 spawnPosition = transform.position + Vector3.up * effectHeight;

        ObtainGems(GameInit.instance.MapData.map_color[id].Item2);

        //GameObject game= Instantiate(Obtain_gems(GameInit.instance.MapData.map_color[id].Item2), spawnPosition, Quaternion.identity, gemstonePos);

        Color _c = Color.white;
        if (GameInit.instance.MapData.map_color.ContainsKey(id))
        {
            (string, string, string) str = GameInit.instance.MapData.map_color[id].Item1;
            // 安全解析 RGB 值（处理可能的格式错误）
            if (float.TryParse(str.Item1, out float r) &&
                float.TryParse(str.Item2, out float g) &&
                float.TryParse(str.Item3, out float b))
            {
                // 如果输入是 0-255 的整数，需归一化到 0-1
                if (r > 1f || g > 1f || b > 1f)
                {
                    r /= 255f;
                    g /= 255f;
                    b /= 255f;
                }
                _c = new Color(r, g, b);
            }
        }
        if(iswrite)
        {
            ReadData.instance.WriteData(QueueId - 1);
        }
        CurrentGems.transform.Find("Cubie").transform.GetComponent<Renderer>().material.color = _c;

        GameInit.instance.Painting(id);
        ChangePanel.changePanel.Progress(id);
        ColoringEffect();
        TurnOffConsumption();
    }
    /// <summary>
    /// 切换宝石
    /// </summary>
    /// <param name="str"></param>
    private void ObtainGems(string str)
    {
        Turn0ffGems();
        switch (str)
        {
            case "五边型":
                CurrentGems = Pentagonal_type;
                Pentagonal_type.gameObject.SetActive(true);
                break;
            case "八边型":
                CurrentGems = paintEffectPrefab;
                paintEffectPrefab.gameObject.SetActive(true);
                break;
            case "砖石":
                CurrentGems = masonry;
                masonry.gameObject.SetActive(true);
                break;
        }
    }

    private void Turn0ffGems()
    {
        Pentagonal_type.gameObject.SetActive(false);
        paintEffectPrefab.gameObject.SetActive(false);
        masonry.gameObject.SetActive(false);
    }



    /// <summary>
    /// 宝石形状
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    private GameObject Obtain_gems(string str)
    {
        GameObject go = Pentagonal_type;
        switch (str)
        {
            case "五边型":
                go = Pentagonal_type;
                break;
            case "八边型":
                go = paintEffectPrefab;
                break ;
            case "砖石":
                go = masonry;
                break ;

        }
        return go;
    }



}
